package com.xz.knowledgeDuplication.thread;

/**
 * 死锁: 多个线程互相拥有着对方需要的资源,然后线程僵持
 * 产生死锁的条件: 互斥/请求与保持/不可剥夺/循环等待
 * @author 召
 * @date 2022-07-26 21:07:36
 */
public class DeadLock {

    public static void main(String[] args) {
        new Thread(new Makeup(0), "小张").start();
        new Thread(new Makeup(1), "小陈").start();
    }

}

/**
 * 口红
 */
class Lipstick {
}

/**
 * 镜子
 */
class Mirror {
}

class Makeup implements Runnable {

    /**
     * 口红 资源只有一份需要用static关键字保证
     */
    private static Lipstick lipstick = new Lipstick();

    /**
     * 镜子 资源只有一份需要用static关键字保证
     */
    private static Mirror mirror = new Mirror();

    /**
     * 选择
     */
    private int choice;

    public Makeup(int choice) {
        this.choice = choice;
    }

    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 化妆
     * @throws InterruptedException
     */
    private void makeup() throws InterruptedException {
        //
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(Thread.currentThread().getName() + "拿到了口红");
                Thread.sleep(1000);
                synchronized (mirror) {
                    System.out.println(Thread.currentThread().getName() + "拿到了镜子");
                }
            }
        } else {
            synchronized (mirror) {
                System.out.println(Thread.currentThread().getName() + "拿到了镜子");
                Thread.sleep(1000);
                synchronized (lipstick) {
                    System.out.println(Thread.currentThread().getName() + "拿到了口红");
                }
            }
        }
    }
}